
package com.scalar.chiptrack.operations.dataentry.actions;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.StringTokenizer;
import java.sql.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.adaptor.FabSortLot;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.dataentry.forms.FabDataEntryForm;
import com.scalar.chiptrack.operations.process.Lot;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.LotDAO;
import com.scalar.chiptrack.operations.process.dao.PartNumber;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.Functionality;

public final class FabDataEntryAction extends ChipTrackAction
{
    private static final String ACTION_NAME = "/fabDataEntry.do" ;
    public FabDataEntryAction ()
    {
    }

    public ActionForward execute ( ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response ) throws Exception
    {
        HttpSession session = request.getSession ();
        User user = ( User ) session.getAttribute ( SessionKeys.USER_KEY );

        if ( user == null )
		{
            session.setAttribute ( SessionKeys.SOURCE_PAGE_KEY,  ACTION_NAME );
			return ( mapping.findForward ( "login" ) );
		}
        else
        {
            if ( user.isActionAllowed ( Functionality.DATA_ENTRY, User.USER_ACTION_MODIFY ) )
            {
                request.setAttribute ( "showMessage", "FALSE" );
            }
            else
            {
                request.setAttribute ( "showMessage", "TRUE" );
            }
        }

        ArrayList partNumberList 		= new ArrayList ();
		ArrayList partNumberSelectList 	= new ArrayList ();
		ArrayList fabLocationList      	= null;
		ArrayList vendorLocationList    = new ArrayList ();
		HashMap info 					= new LinkedHashMap();
		HashMap errors 					= new LinkedHashMap();
		VendorLocation vendorLocation   = null;
		PartNumber partNumber 			= null;
		String actionForward			= "success";
		boolean success 				= false;

        FabDataEntryForm fabDataEntryForm = ( FabDataEntryForm ) form;

        String action 	= request.getParameter ( "action" );
		String confirm 	= request.getParameter ( "confirm" );

        if ( action == null )
            action = "";
        request.setAttribute ( "action", action );
		if ( confirm == null )
			confirm = "";

        partNumberList = ProductDao.getPartNumber( "FAB" );

        for ( int i = 0; i < partNumberList.size (); i++ )
        {
            partNumber = ( PartNumber ) partNumberList.get ( i );
            partNumberSelectList.add ( new org.apache.struts.util.LabelValueBean ( partNumber.getPartNumber (), partNumber.getProcessStepId () + "$" + partNumber.getPartNumber () ) );
        }

        request.setAttribute ( "partNumberSelectList", partNumberSelectList );

        if ( action.equals ( "" ) )
        {
            return ( mapping.findForward ( "success" ) );
        }

        String locationId       = fabDataEntryForm.getLocationId ();
        String processStepId    = fabDataEntryForm.getProcessStepId ();
        String quantityIn       = fabDataEntryForm.getQuantityIn ();
        String quantityOut      = fabDataEntryForm.getQuantityOut ();
        String dateIn           = fabDataEntryForm.getDateIn ();
        String dateOut          = fabDataEntryForm.getDateOut ();
        String lotId            = fabDataEntryForm.getLotId ();
        String dateCode         = fabDataEntryForm.getDateCode ();
        String vendorLot        = fabDataEntryForm.getVendorLot ();
        String comments         = fabDataEntryForm.getComments ();
		String poNumber 		= "";

        if ( action.equals ( "location" ) || action.equals ( "save" ) || action.equals ( "lotnumber" ) || action.equals ( "partnumber" ) )
        {
            StringTokenizer st1 = new StringTokenizer ( processStepId, "$" );
            String pId = st1.nextToken ();
            st1.nextToken ();

            fabLocationList = VendorDAO.getSelectedLocations ( Integer.parseInt ( pId ) );
            for ( int i = 0; i < fabLocationList.size (); i++ )
            {
                vendorLocation = ( VendorLocation ) fabLocationList.get ( i );
                vendorLocation.setLocationID ( vendorLocation.getLocationID () );
                vendorLocation.setLocationName ( vendorLocation.getLocationName () );
                vendorLocationList.add ( new org.apache.struts.util.LabelValueBean ( vendorLocation.getLocationName (), vendorLocation.getLocationID () + "/" + vendorLocation.getLocationName () ) );
            }
            request.removeAttribute("locationSelectList");

            request.setAttribute ( "locationSelectList", vendorLocationList );
        }

        if ( action.equals ( "location" ) || action.equals ( "lotnumber" ) || action.equals ( "save" ) )
        {
            ArrayList list = getLotList(processStepId, locationId);
            request.setAttribute ( "lotNumbers", list );
            if ( action.equals ( "location" ) )
            {
                fabDataEntryForm.setLotId("0");
            }
        }

        if ( action.equals ( "lotnumber" ) )
        {
            if ( ( !"-1".equals ( lotId ) ) )
            {
                StringTokenizer st = new StringTokenizer ( fabDataEntryForm.getLotId (), "$" );
                String strLotId = st.nextToken ();
                st.nextToken ();
                st.nextToken ();
                poNumber = "";

                Lot lot = LotDAO.getFabLotData  ( strLotId );

                if( lot.getPOrderID() != null && lot.getPOrderID().trim().length() != 0 )
				{
                    poNumber = lot.getPOrderID();
				}
				else
				{
                    poNumber = "";
                }

                fabDataEntryForm.setQuantityIn  ( lot.getQuantityIn () );
                fabDataEntryForm.setQuantityOut ( lot.getQuantityOut () );
                fabDataEntryForm.setDateIn      ( lot.getDateIn () );
                fabDataEntryForm.setDateOut     ( lot.getDateOut () );
				fabDataEntryForm.setGrossDie	( lot.getGrossDie () );
				fabDataEntryForm.setPoNumber	( poNumber );
                fabDataEntryForm.setDateCode 	( lot.getDateCode () );
                fabDataEntryForm.setVendorLot 	( lot.getVendorLot () );
                fabDataEntryForm.setComments 	( lot.getComments () );
                fabDataEntryForm.setWaferId    ( lot.getWaferId() );
            }
            else
            {
				String pId = processStepId.substring(0, processStepId.indexOf("$"));
				String grossDieSize[] = LotDAO.getGrossDieWafer(null, pId);
				if ( ( grossDieSize !=null ) && (grossDieSize.length > 0 ) )
				{
					fabDataEntryForm.setGrossDie ( grossDieSize[0] );
				}
				else
				{
					fabDataEntryForm.setGrossDie ("");
				}

				fabDataEntryForm.setLotNo       ( "" );
                fabDataEntryForm.setQuantityIn  ( "" );
                fabDataEntryForm.setQuantityOut ( "" );
                fabDataEntryForm.setDateIn      ( StringUtils.formatDateToString(new Date(System.currentTimeMillis()), "MM/dd/yyyy") );
                fabDataEntryForm.setDateOut     ( "" );
				fabDataEntryForm.setPoNumber	( "" );
                fabDataEntryForm.setDateCode	( "" );
                fabDataEntryForm.setVendorLot	( "" );
                fabDataEntryForm.setComments	( "" );
            }
            saveToken( request );
            request.setAttribute ( "lotnumber", "true" );
        }

        if( "allLotInfo".equals( action ) )
        {

            String lotprocessstepId = request.getParameter("ProcessStepId");
            String lotlocationId = request.getParameter("LocationId");
            String lotNo         = request.getParameter("LotNo");

            StringTokenizer st = new StringTokenizer ( lotprocessstepId, "$" );
            String pId = st.nextToken ();
            st.nextToken ();

            st = new StringTokenizer ( lotlocationId, "/" );
            String locId = st.nextToken ();
            st.nextToken ();

            ArrayList allLotsList = null;

            try
            {
                String newlotId = LotDAO.getLotId( lotNo , locId, pId  );

                if ( newlotId != null && newlotId.length() > 0 )
                {
                    allLotsList = LotDAO.getAllLotDetails( newlotId );
                }

                request.setAttribute("allLotsList", allLotsList );
            }
            catch( Exception e )
            {
                e.printStackTrace();
                errors.put( "Error while retreiving the Lot history list", null );
            }
            return mapping.findForward( "alllotInfo" );
        }

        if ( action.equals ( "save" ) )
        {
            if ( quantityIn.equals ( "" ) )
            {
                quantityIn = null;
            }

            if ( dateIn.equals ( "" ) )
            {
                 dateIn = null;
            }

            if ( quantityOut.trim().equals ( "" ) )
            {
                quantityOut = null;
            }

            if ( dateOut.equals ( "" ) )
            {
                dateOut = null;
            }

            if ( dateCode.equals ( "" ) )
            {
                dateCode = null;
            }

            String lotCurrentStatus = "Running";

            if( quantityOut != null )
            {
                lotCurrentStatus = "Close";
            }

            //commented by Sujan on 6th july 2005 as we don't have partial shipment for fab data entry for matrix
			/*try
			{
				if( Integer.parseInt( quantityIn ) == Integer.parseInt( fabDataEntryForm.getPartialShipQtyIn() ) )
				{
					lotCurrentStatus = "Close";
				}
			}
			catch( Exception e ){}*/
           
            if( isTokenValid( request ) )
            {
	            try
	            {
					//check for duplication or lot number repetition.
					//***** This part of code does nothing but warns that this lot number already exists
					StringTokenizer stok1 = new StringTokenizer (processStepId,"$");
					StringTokenizer stok2 = new StringTokenizer (locationId,"/");
					String procStepId 	= stok1.nextToken();
					String locatId 		= stok2.nextToken();
                    String lot_ID 		= LotDAO.getLotIdInDataEntry ( null, procStepId, locatId, fabDataEntryForm.getLotNo() );
					if(lot_ID == null)
					{
						lot_ID = "";
					}
	
					lot_ID = lot_ID.trim();
	
					if( lotId.equals ( "-1" ) && ( !confirm.equals( "confirm" ) ) )
					{
						if ( "".equalsIgnoreCase(lot_ID)==false)
						{
                            request.setAttribute( "showError", "TRUE" );
							return mapping.findForward( "success" );
						}
					}
					//*************

					DBTransaction dbTransaction = null;
					try
					{
						dbTransaction = DBTransaction.getInstance ();
						dbTransaction.begin ();
					}
					catch ( Exception e )
					{
						e.printStackTrace ();
					}
	
					// Step 1 : Save fab_lot table
					String strLotId = null;
					String strLotNo = null;
	
					if ( !lotId.equals ( "-1" ) )
					{
						StringTokenizer st = new StringTokenizer ( fabDataEntryForm.getLotId (), "$" );
						strLotId = st.nextToken ();
						strLotNo = st.nextToken ();
						st.nextToken ();
					}
					else
					{
						strLotId = "-1";
						strLotNo = fabDataEntryForm.getLotNo ();
					}
	
					StringTokenizer st1 = new StringTokenizer ( processStepId, "$" );
					st1.nextToken ();
					String pNumber = st1.nextToken ();
	
					st1 = new StringTokenizer ( fabDataEntryForm.getLocationId (), "/" );
					st1.nextToken ();
					String vendorName = st1.nextToken ();
	
					poNumber = fabDataEntryForm.getPoNumber();
	
					FabSortLot wipSummary = new FabSortLot ();
	
					wipSummary.setCustProduct   ( pNumber );
					wipSummary.setDateIn        ( dateIn );
					wipSummary.setDateOut       ( dateOut );
					wipSummary.setQtyIn         ( quantityIn );
					wipSummary.setQtyOut        ( quantityOut );
					wipSummary.setLotStatus     ( lotCurrentStatus );
					wipSummary.setLotId         ( strLotNo );
					wipSummary.setVendorName    ( vendorName );
					wipSummary.setPoNumber		( poNumber );
					wipSummary.setDateCode		( dateCode );
					wipSummary.setVendorLot		( vendorLot );
					wipSummary.setComments		( comments );
                    //commented by Sujan on 6th july 2005 as we don't have partial shipment for fab data entry for matrix
					/*wipSummary.setPartialshipQtyIn( fabDataEntryForm.getPartialShipQtyIn() );
					wipSummary.setPartialshipQtyOut( fabDataEntryForm.getPartialShipQtyOut() );
					wipSummary.setPartialShipDateOut( fabDataEntryForm.getPartialShipDateOut() );*/
	
					if ( ( ( fabDataEntryForm.getGrossDie() != null ) && ( fabDataEntryForm.getGrossDie().equalsIgnoreCase( "null" ) ) ) || ( fabDataEntryForm.getGrossDie() == null ) || ( fabDataEntryForm.getGrossDie().trim().length() == 0 ) )
					{
						wipSummary.setGrossDie ( null );
					}
					else
					{
						wipSummary.setGrossDie ( fabDataEntryForm.getGrossDie() );
					}
	

                    wipSummary.setWaferID( fabDataEntryForm.getWaferId() );
					ArrayList wipSummaryList = new ArrayList ();
					wipSummaryList.add ( wipSummary );
	
					// To update the lot_current_status to close from running. 
					if( strLotId != null && !strLotId.equalsIgnoreCase( "-1" ) )
					{
						LotDAO.changeLotStatusToCloseByLotId(dbTransaction, strLotId);
					}
	
					LotDAO.saveFabLot ( dbTransaction, wipSummaryList, user.getUserName () );
					
					resetToken( request );
	
					success	= true;
	
					try
					{
						if( dbTransaction != null )
						{
							if( success == true )
							{
								dbTransaction.commit();
							}
							else
							{
								dbTransaction.rollback();
							}
						}
					}
					catch(Exception e1)
					{
						e1.printStackTrace();
					}
					info.put( "Data has been updated successfully", "");
					actionForward = "saveSuccess";
	            }
				catch( Exception e )
				{
					e.printStackTrace();
					errors.put( "Could not save the lot information ", null );
				}
            }
            else
            {
				errors.put( "Lot Information already saved", null );
				actionForward = "saveSuccess";
            }
        }

		if ( action.equals( "null" ) )
		{
			fabDataEntryForm.setProcessStepId( "0" );
			request.setAttribute( SessionKeys.INFO_MESSAGES, request.getAttribute( SessionKeys.INFO_MESSAGES ) );
			request.setAttribute( SessionKeys.ERROR_MESSAGES, request.getAttribute( SessionKeys.ERROR_MESSAGES ) );
		}
		else
		{
			request.setAttribute( SessionKeys.INFO_MESSAGES, info );
			request.setAttribute( SessionKeys.ERROR_MESSAGES, errors );
		}
		
        request.removeAttribute ( "fabdataentryform" );
        request.setAttribute ( "fabdataentryform", fabDataEntryForm );
        return ( mapping.findForward ( actionForward ) );
    }

    private ArrayList getLotList(String processStepId, String locationId)
    {
        java.util.ArrayList list = new ArrayList();
        try
        {
            StringTokenizer st = new StringTokenizer ( processStepId, "$" );
            String pId = st.nextToken ();
            st.nextToken ();

            st = new StringTokenizer ( locationId, "/" );
            String locId = st.nextToken ();
            st.nextToken ();

            ArrayList lotNumberList = LotDAO.getRunningLotNumbersByPSTypeName ( pId, locId, "FAB" );
            Lot lot = null;
            list = new java.util.ArrayList ();

            for ( int i = 0; i < lotNumberList.size (); i++ )
            {
                lot = ( Lot ) lotNumberList.get ( i );
                list.add ( new org.apache.struts.util.LabelValueBean ( lot.getLotNumber (), lot.getLotId () + "$" + lot.getLotNumber () + "$" + lot.getStatus () ) );
            }
        }
        catch(Exception e)
        {

        }
        return list;
    }
}